import os
from core.geometry_creator import GeometryCreator
from file_io.file_saver import save_geometry
from file_io.ifc_exporter import create_ifc_model
from utils.config import get_output_paths


def main():
    try:
        # 获取当前工作目录
        current_dir = os.getcwd()
        print(f"当前工作目录: {current_dir}")

        # 创建输出目录
        output_paths = get_output_paths()
        for path in output_paths.values():
            os.makedirs(path, exist_ok=True)
        print(f"创建输出目录: {output_paths['base']}")

        creator = GeometryCreator()

        while True:
            try:
                # 获取用户输入的参数
                C = float(input("请输入底座长度C（米，输入0退出）: "))
                if C <= 0:
                    break

                S1 = float(input("请输入上部梯形台的上底边长度S1（米）: "))
                if S1 <= 0:
                    print("错误：S1必须大于0")
                    continue

                S2 = float(input("请输入上部梯形台的下底边长度S2（米）: "))
                if S2 <= 0:
                    print("错误：S2必须大于0")
                    continue

                H1 = float(input("请输入上部梯形台高度H1（米）: "))
                if H1 <= 0:
                    print("错误：H1必须大于0")
                    continue

                H2 = float(input("请输入下部长方体高度H2（米）: "))
                if H2 <= 0:
                    print("错误：H2必须大于0")
                    continue

                print(f"\n开始批量生成模型...")
                print(f"底座长度: {C}m")
                print(f"上部梯形台上底边长度: {S1}m")
                print(f"上部梯形台下底边长度: {S2}m")
                print(f"上部梯形台高度: {H1}m")
                print(f"下部长方体高度: {H2}m")

                # 以5度为间隔生成模型
                for alpha in range(30, 65, 5):  # 30度到60度，步长5度
                    print(f"\n正在生成 {alpha}° 的模型...")

                    try:
                        # 创建几何体
                        mesh, volume, area = creator.create_slope(
                            C=C, S1=S1, S2=S2, H1=H1, H2=H2,
                            alpha=alpha, width=5.0
                        )

                        # 保存网格模型
                        try:
                            saved_files = save_geometry(mesh, "", alpha, C, S1, S2, H1, H2)
                            if saved_files:
                                print(f"✓ {alpha}° 网格模型已保存: {len(saved_files)} 个文件")
                            else:
                                print(f"✗ {alpha}° 网格模型保存失败")
                        except Exception as mesh_error:
                            print(f"✗ {alpha}° 网格模型保存失败: {str(mesh_error)}")

                        # 生成IFC模型
                        try:
                            ifc_path = create_ifc_model(mesh, alpha, C, volume, area)
                            if ifc_path and os.path.exists(ifc_path):
                                print(f"✓ {alpha}° IFC模型已保存: {ifc_path}")
                                print(f"  - 文件大小: {os.path.getsize(ifc_path) / 1024:.1f} KB")
                            else:
                                print(f"✗ {alpha}° IFC模型保存失败")
                        except Exception as ifc_error:
                            print(f"✗ {alpha}° IFC模型生成失败: {str(ifc_error)}")

                        print(f"✓ {alpha}° 模型处理完成")
                        print(f"  - 填筑体积: {volume:.2f} m³")
                        print(f"  - 征地面积: {area:.2f} m²")

                    except Exception as e:
                        print(f"✗ {alpha}° 模型生成失败：{str(e)}")
                        continue

                print("\n所有角度的模型生成完成！")
                print(f"网格文件保存在: {output_paths['mesh']}")
                print(f"IFC文件保存在: {output_paths['ifc']}")

            except ValueError as e:
                print(f"输入错误：{str(e)}")
            except Exception as e:
                print(f"未预期的错误：{str(e)}")
                import traceback
                traceback.print_exc()

    except Exception as e:
        print(f"程序初始化错误: {str(e)}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()